<template>
	<view class="content">

		<u-navbar class="navbar" :fixed="false" title="批次绑定" titleWidth="700" :autoBack="true" :safeAreaInsetTop="true"
			leftIconColor="#fff">
			<view class="u-nav-slot" slot="left">
				<view class="NavbarLeft">
					<!-- 回退按钮 -->
					<u-icon name="arrow-left" :duration="0" size="20" color="#fff" @click="GoBack"></u-icon>
				</view>
			</view>

		</u-navbar>


		<view class="contentBox">
			<view class="container">
				<uni-forms ref="baseForm" :modelValue="baseFormData">
					<view class="form-item-row">
						<uni-forms-item label="绑定日期:" label-width="auto">
							<input v-model="baseFormData.BillDate" type="text" placeholder="请选择日期" disabled
								@click="Timeshow=true;" />
						</uni-forms-item>

						<uni-forms-item label="单据编号:" label-width="auto">
							<input v-model="baseFormData.BillNO" type="text" placeholder="" disabled />
						</uni-forms-item>

						<uni-forms-item label="生产车间:" label-width="auto">
							<input v-model="baseFormData.FWorkshopName" type="text" placeholder="扫码带出生产车间" disabled />
						</uni-forms-item>
					</view>
				</uni-forms>
			</view>
			<view class="table" style="width: 96%;text-align: center;margin: auto;">
				<table>
					<tr>
						<th width='20%'>工单编号</th>
						<th width='21%'>派工单编号</th>
						<th>产品编码</th>
						<th>产品名称</th>
						<th>产品规格</th>
						<th width='12%'>绑定状态</th>
						<th width='10%' v-if="!baseFormData.TraceID">操作</th>
					</tr>
					<tr v-for="(item,index) in formData" :key="index" @click="clickpopup_show(item)">
						<td>{{item.GDBillNO}}</td>
						<td>{{item.PGDBillNO}}</td>
						<td>{{item.ProductCode}}</td>
						<td>{{item.ProductName}}</td>
						<td>{{item.ProductSpec}}</td>
						<td :style="getBindStyleByID(item.BindStatus)">{{getBindNameByID(item.BindStatus)}}
						</td>
						<td v-if="!baseFormData.TraceID">
							<view>
								<u-button type="warning" size="small" text="删除"
									@click.native.stop="formData_del(index,item)"></u-button>
							</view>
						</td>
					</tr>
				</table>
				<view class="Detailsbutton">
					<button v-if="!baseFormData.TraceID" class="button1" block @click="submit_Add">
						提交
					</button>
					<button v-if="baseFormData.TraceID" class="button1" block @click="submit_Edit">
						修改
					</button>
				</view>
			</view>
		</view>
		<view class="search" v-if="!baseFormData.TraceID" @click="scan" style="z-index: 1;width: 80rpx;height: 80rpx;">
			<u-icon name="scan" color="#fff" size="80rpx"></u-icon>
		</view>


		<u-datetime-picker :show="Timeshow" v-model="value1" mode="date" @cancel='Timeshow=false'
			@confirm='pickerConfirm'></u-datetime-picker>

		<u-popup :show="popup_show" mode="center" :closeOnClickOverlay="false"
			:customStyle="{height:'80%',width:'80%'}">
			<view class="contentBox">
				<view class="container">
					<uni-forms ref="batchForm" :modelValue="batchFormData">
						<view class="form-item-row form-item-row1">

							<uni-forms-item label="派工单号:" label-width="auto">
								<input v-model="batchFormData.PGDBillNO" type="text" placeholder="" disabled />
							</uni-forms-item>

							<uni-forms-item label="产品编码:" label-width="auto">
								<input v-model="batchFormData.ProductCode" type="text" placeholder="" disabled />
							</uni-forms-item>

							<uni-forms-item label="产品名称:" label-width="auto">
								<input v-model="batchFormData.ProductName" type="text" placeholder="" disabled />
							</uni-forms-item>

							<uni-forms-item label="产品规格:" label-width="auto">
								<input v-model="batchFormData.ProductSpec" type="text" placeholder="" disabled />
							</uni-forms-item>
						</view>
					</uni-forms>
				</view>
				<view class="table" style="width: 96%;text-align: center;margin: auto;">
					<table>
						<tr>
							<th>物料编码</th>
							<th>物料名称</th>
							<th>物料规格</th>
							<th>批次号</th>
							<th width='12%'>数量</th>
							<th width='10%'>操作</th>
						</tr>
						<tbody>

							<tr v-for="(batchItem,index) in batchList" :key="index">
								<td>{{batchItem.ProductCode}}</td>
								<td>{{batchItem.ProductName}}</td>
								<td>{{batchItem.ProductSpec}}</td>
								<!-- <td>{{batchItem.FBatchNo}}</td> -->
								<td>
									<view class="td_view">
										<view class="ListTdDiv"><text>{{batchItem.FBatchNo}}</text></view>
										<view class="SOPView" v-if="batchItem.FBatchNo" @click="clearFBatchNo(index)">
											<u-icon name="trash" size="30"></u-icon>
										</view>
									</view>

								</td>
								<td>
									<input v-model="batchItem.FQty" type="digit" placeholder="请输入" />
								</td>
								<td>
									<view>
										<u-button type="warning" size="small" text="删除"
											@click.native.stop="batchList_del(index,batchItem)"></u-button>
									</view>
								</td>
							</tr>

						</tbody>

					</table>
				</view>

				<view class="search" @click="scan1" style="z-index: 1;width: 80rpx;height: 80rpx;">
					<u-icon name="scan" color="#fff" size="80rpx"></u-icon>
				</view>

				<view class="Detailsbutton">
					<button class="button1" block @click="submit_batch" style="margin-left: 20%;">
						确定
					</button>
				</view>

			</view>
		</u-popup>


	</view>

</template>
<script>
	import {
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime
	} from '../common/base.js';
	export default {
		data() {
			return {
				baseFormData: {
					TraceID: 0,
					BillDate: '',
					BillNO: '自动生成',
					FWorkshopID: 0,
					FWorkshopName: '',

				},

				formData: [],

				popup_show: false,
				batchFormData: {
					PGDBillNO: '',
					ProductCode: '',
					ProductSpec: '',
				},
				batchList: [],

				value1: Number(new Date()),
				Timeshow: false,

			};
		},

		mounted() {},
		onLoad(option) {
			console.log(JSON.stringify(option))
			if (option.TraceID) {
				this.baseFormData.TraceID = option.TraceID;
				this.getDetail();
			} else {
				this.baseFormData.BillDate = getFormatDateTime(new Date());
			}

		},
		onShow() {
			plus.screen.lockOrientation('landscape-primary');
		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		methods: {
			GoBack() {
				uni.navigateBack()
			},
			getBindStyleByID(id) {
				let obj = {

				}
				switch (id) {
					case 0:
						obj = {
							color: 'red'
						}
						break;
					case 1:
						obj = {
							color: 'red'
						}
						break;
					case 2:
						obj = {
							color: 'green'
						}
						break;
					default:
						obj = {}
				}

				return obj
			},
			getBindNameByID(id) {
				let name = ''
				switch (id) {
					case 0:
						name = '未绑定'
						break;
					case 1:
						name = '部分绑定'
						break;
					case 2:
						name = '全部绑定'
						break;
					default:
						name = ''
				}

				return name
			},
			getBindStatus(item) {
				let that = this;

				let BindStatus = 0;

				try {
					if (item.batchList.every((ele) => {
							return ele.FBatchNo
						})) {
						BindStatus = 2;
					} else if (item.batchList.every((ele) => {
							return !ele.FBatchNo
						})) {
						BindStatus = 0;
					} else if (item.batchList.some((ele) => {
							return !ele.FBatchNo
						})) {
						BindStatus = 1;
					}
				} catch (e) {
					console.log(e);
					BindStatus = 0;
				}


				return BindStatus

			},
			TakeBindStatus() {
				let that = this;
				that.formData.forEach((data) => {
					data.BindStatus = that.getBindStatus(data)
				})
			},
			getDetail() {
				let that = this;
				let obj = {
					TraceID: that.baseFormData.TraceID
				}
				that.Request.request('batchTraceDetail', obj, function(res) {
					if (res.status == 200) {
						that.baseFormData.TraceID = res.data.ds[0].TraceID;
						that.baseFormData.BillDate = res.data.ds[0].BillDate;
						that.baseFormData.BillNO = res.data.ds[0].BillNO;
						that.baseFormData.FWorkshopID = res.data.ds[0].FWorkshopID;
						that.baseFormData.FWorkshopName = res.data.ds[0].FWorkshopName;

						let obj = {
							JobOrderID: res.data.ds[0].JobOrderID,
							PGDBillNO: res.data.ds[0].PGDBillNO,
							WoOrderID: res.data.ds[0].WoOrderID,
							GDBillNO: res.data.ds[0].GDBillNO,
							ProductID: res.data.ds[0].ProductID,
							ProductCode: res.data.ds[0].ProductCode,
							ProductName: res.data.ds[0].ProductName,
							ProductSpec: res.data.ds[0].ProductSpec,
						}

						let batchList = [];
						if (res.data.ds1 && res.data.ds1.length) {
							batchList = res.data.ds1
						}
						obj.batchList = batchList;

						that.formData = [obj]
						that.TakeBindStatus()
						console.log(that.formData)
						that.$forceUpdate()

						Promise.resolve().then(() => {
							that.clickpopup_show(that.formData[0]);
						})

					} else {
						that.$utils.msg('请求失败，请重试');
					}
				}, function(err) {
					console.log(JSON.stringify(err))
				})
			},
			pickerConfirm(e) {
				let that = this;
				var time = getFormatDateTime(e.value)
				this.baseFormData.BillDate = time
				this.Timeshow = false
				this.$forceUpdate()
			},
			scan() {
				let that = this;
				this.$scanPopup.openScan({
					scanType: ['qrCode'],
					success: (data) => {
						console.log(JSON.stringify(data))
						let IsPGD = false;
						try {
							IsPGD = (data.result.split('|')[0] == 'PGD')
						} catch (e) {
							IsPGD = false;
						}
						if (IsPGD) {
							let obj = {
								JobOrderID: data.result.split('|')[1],
								FWorkshopID: that.baseFormData.FWorkshopID
							}
							that.Request.request('batchTraceScan', obj, function(res) {
								if (res.status == 200) {
									if (res.data.ds[0].status && res.data.ds[0].status == 500) {
										that.$utils.msg(res.data.ds[0].msg);
									} else {
										if (!that.baseFormData.FWorkshopID) {
											that.baseFormData.FWorkshopID = res.data.ds[0].FWorkshopID;
											that.baseFormData.FWorkshopName = res.data.ds[0]
												.FWorkshopName;
										}
										let isExists = that.formData.some((item) => {
											return item.JobOrderID == res.data.ds[0].JobOrderID
										})
										if (isExists) {
											that.$utils.msg('当前扫描的派工单已存在！！');
										} else {
											let SearchBatchList = that.formData.filter((item) => {
												return item.ProductID == res.data.ds[0]
													.ProductID && item.WoOrderID == res.data
													.ds[0]
													.WoOrderID
											})

											if (SearchBatchList.length) {
												res.data.ds[0].batchList = SearchBatchList[0]
													.batchList || []
											} else {
												res.data.ds[0].batchList = res.data.ds1 || []
											}

											that.formData.push(res.data.ds[0])

											that.formData.sort((a, b) => {
												return a.ProductID - b.ProductID && a
													.WoOrderID - b.WoOrderID
											})

											that.TakeBindStatus()
										}


									}
								} else {
									that.$utils.msg('请求失败，请重试');
								}
							}, function(err) {
								console.log(JSON.stringify(err))
							})

						} else {
							that.$utils.msg('请扫描派工单二维码');
						}
					}
				})
			},
			scan1() {
				let that = this;
				this.$scanPopup.openScan({
					scanType: ['qrCode'],
					success: (data) => {
						console.log(JSON.stringify(data))
						let IsPCM = false;
						try {
							IsPCM = (data.result.split('|')[0] == 'CPPCM')
						} catch (e) {
							IsPCM = false;
						}
						if (IsPCM) {
							let obj = {
								code: data.result.split('|')[1],
								batch: data.result.split('|')[2],
								JobOrderID: that.batchFormData.JobOrderID,
							}
							console.log(obj)
							that.Request.request('batchTraceScan_PCM', obj, function(res) {
								if (res.status == 200) {
									if (res.data.ds[0].status && res.data.ds[0].status == 500) {
										that.$utils.msg(res.data.ds[0].msg);
									} else {
										let isExists_Product = that.batchList.some((item) => {
											return item.ProductID == res.data.ds[0]
												.ProductID
										})
										if (!isExists_Product) {
											that.$utils.msg('请扫描与当前领料明细物料一致的物料批次码！！');
										} else {
											let isExists_Product_FBatchNo = that.batchList.some((
												item) => {
												return item.ProductID == res.data.ds[0]
													.ProductID &&
													item.FBatchNo == res.data.ds[0].FBatchNo
											})
											if (isExists_Product_FBatchNo) {
												that.$utils.msg('当前扫描的物料批次码已存在！！');
											} else {
												let matchList = [];
												matchList = that.batchList.filter((ele) => {
													return ele.ProductID == res.data.ds[0]
														.ProductID && !
														ele.FBatchNo
												})
												if (matchList.length == 1) {
													that.batchList.find((ele) => {
														return ele.ProductID == res.data.ds[0]
															.ProductID && !
															ele.FBatchNo
													}).FBatchNo = res.data.ds[0].FBatchNo;
												} else {
													that.batchList.push(res.data.ds[0])
													that.batchList.sort((a, b) => {
														return a.ProductID - b.ProductID
													})
												}
											}
										}



									}
								} else {
									that.$utils.msg('请求失败，请重试');
								}
							}, function(err) {
								console.log(JSON.stringify(err))
							})

						} else {
							that.$utils.msg('请扫描物料批次码');
						}
					}
				})
			},
			formData_del(index, item) {
				var that = this;
				let content = '是否删除此条数据？'
				if (item.BindStatus == 2) {
					content = '该条派工单数据已全部绑定批次，是否删除此条数据？'
				}
				uni.showModal({
					title: '提示',
					content: content,
					success: function(res) {
						if (res.confirm) {
							that.formData.splice(index, 1);
							if (!that.formData.length) {
								that.baseFormData.FWorkshopID = 0;
								that.baseFormData.FWorkshopName = '';
							}
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				})
			},
			batchList_del(index, item) {
				var that = this;
				uni.showModal({
					title: '提示',
					content: '是否删除此条数据？',
					success: function(res) {
						if (res.confirm) {
							let matchList = [];
							matchList = that.batchList.filter((ele) => {
								return ele.ProductID == item.ProductID
							})
							if (matchList.length == 1) {
								that.$utils.msg('请至少保留一行该物料！！');
							} else {
								that.batchList.splice(index, 1);
							}

						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				})
			},
			clearFBatchNo(index) {
				var that = this;
				uni.showModal({
					title: '提示',
					content: '是否清除该批次？',
					success: function(res) {
						if (res.confirm) {
							that.batchList[index].FBatchNo = '';
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				})
			},
			clickpopup_show(item) {
				console.log(item)
				var that = this;
				that.batchFormData = that.$utils.deepClone(item);
				console.log(that.batchFormData)
				that.batchList = item.batchList || [];
				that.popup_show = true;
				this.$forceUpdate()
			},
			submit_Add() {
				var that = this;

				uni.showModal({
					title: '提示',
					content: '是否提交？',
					success: function(res) {
						if (res.confirm) {
							if (!that.formData.length) {
								that.$utils.msg('派工单列表不能为空！！');
								return
							}
							if (that.formData.some((item) => {
									return item.BindStatus != 2;
								})) {
								that.$utils.msg('存在未全部绑定批次的派工单！！');
								return
							}
							let FBatchNos = [],
								ProductIDs = [],
								FQtys = [],
								JobOrderIDs = []
							that.formData.forEach((item) => {
								if (item.batchList && item.batchList.length) {
									item.batchList.forEach((ele) => {
										FBatchNos.push(ele.FBatchNo);
										ProductIDs.push(ele.ProductID);
										FQtys.push(ele.FQty);
										JobOrderIDs.push(item.JobOrderID);
									})
								} else {
									FBatchNos.push('');
									ProductIDs.push('');
									FQtys.push('');
									JobOrderIDs.push(item.JobOrderID);
								}
							})

							let obj = {
								BillDate: that.baseFormData.BillDate,
								FWorkshopID: that.baseFormData.FWorkshopID,
								FBatchNos: FBatchNos.join('~'),
								ProductIDs: ProductIDs.join('~'),
								FQtys: FQtys.join('~'),
								JobOrderIDs: JobOrderIDs.join('~')
							}
							console.log(obj)

							that.Request.request('batchTraceSubmit', obj, function(res) {
								if (res.status == 200) {
									if (res.data.ds[0].status && res.data.ds[0].status == 500) {
										that.$utils.msg(res.data.ds[0].msg);
									} else {

										that.$utils.msg(res.data.ds[0].msg);
										uni.$emit('refresh_batchTrace');
										uni.navigateBack()

									}
								} else {
									that.$utils.msg('请求失败，请重试');
								}
							}, function(err) {
								console.log(JSON.stringify(err))
							})
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				})


			},
			submit_Edit() {
				var that = this;

				uni.showModal({
					title: '提示',
					content: '是否提交修改？',
					success: function(res) {
						if (res.confirm) {
							if (!that.formData.length) {
								that.$utils.msg('派工单列表不能为空！！');
								return
							}
							if (that.formData.some((item) => {
									return item.BindStatus != 2;
								})) {
								that.$utils.msg('存在未全部绑定批次的派工单！！');
								return
							}
							let FBatchNos = [],
								ProductIDs = [],
								FQtys = [],
								JobOrderIDs = []
							that.formData.forEach((item) => {
								if (item.batchList && item.batchList.length) {
									item.batchList.forEach((ele) => {
										FBatchNos.push(ele.FBatchNo);
										ProductIDs.push(ele.ProductID);
										FQtys.push(ele.FQty);
										JobOrderIDs.push(item.JobOrderID);
									})
								} else {
									FBatchNos.push('');
									ProductIDs.push('');
									FQtys.push('');
									JobOrderIDs.push(item.JobOrderID);
								}
							})

							let obj = {
								TraceID: that.baseFormData.TraceID,
								BillDate: that.baseFormData.BillDate,
								FWorkshopID: that.baseFormData.FWorkshopID,
								FBatchNos: FBatchNos.join('~'),
								ProductIDs: ProductIDs.join('~'),
								FQtys: FQtys.join('~'),
								JobOrderIDs: JobOrderIDs.join('~')
							}
							console.log(obj)

							that.Request.request('batchTraceSubmit_Edit', obj, function(res) {
								if (res.status == 200) {
									if (res.data.ds[0].status && res.data.ds[0].status == 500) {
										that.$utils.msg(res.data.ds[0].msg);
									} else {

										that.$utils.msg(res.data.ds[0].msg);

										that.getDetail();

									}
								} else {
									that.$utils.msg('请求失败，请重试');
								}
							}, function(err) {
								console.log(JSON.stringify(err))
							})
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				})
			},
			submit_batch() {
				var that = this;
				that.formData.forEach((item) => {
					if (item.ProductID == that.batchFormData.ProductID && item.WoOrderID == that.batchFormData
						.WoOrderID) {
						item.batchList = that.batchList;
					}
				})
				that.TakeBindStatus()
				console.log(that.formData)
				that.popup_show = false;
			},
		}
	}
</script>

<style lang="scss">
	@import "../css/index.css";

	.form-item-row {
		display: flex;
		flex-wrap: wrap;
	}

	.process_name {
		font-size: 12px !important;
		display: flex;
		justify-content: center;
		width: 100%;
	}

	.selected {
		background-color: yellow !important;
	}

	.table table tr:hover input {
		background-color: transparent;
	}

	.form-item-row1 .uni-forms-item {
		width: 45%;

	}

	.form-item-row1 .uni-forms-item input {
		width: 100vw;
	}

	.DetailsbottomBtns {
		bottom: 10vh;
	}

	.Detailsbutton {
		width: 100%;
		text-align: center;
	}

	.Detailsbutton button {
		margin: 1% 0;
		display: inline-block;
		color: #fff;
		background-color: #51d0d0;
		font-size: 20px;
	}

	.Detailsbutton .button1 {
		width: 40%;
	}

	.td_view {
		display: flex;
		align-items: center;
		border: none;

		.SOPView {
			flex: 1;
			box-sizing: border-box;

			// .u-button {
			// 	width: 10%;
			// 	float: right;
			// 	color: #fff;
			// 	background-color: #51d0d0;
			// 	box-sizing: border-box;
			// }
		}
	}
</style>